<template>
  <div class="create-table-container">
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>新建台桌</span>
        </div>
      </template>

      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          label-position="right"
      >
        <el-form-item label="编号" prop="number">
          <el-input v-model="form.number" placeholder="请输入" clearable />
        </el-form-item>

        <el-form-item label="所属门店" prop="storeId">
          <el-select v-model="form.storeId" placeholder="请选择..." clearable>
            <el-option
                v-for="store in storeOptions"
                :key="store.id"
                :label="store.name"
                :value="store.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="桌号" prop="tableNumber">
          <el-input v-model="form.tableNumber" placeholder="请输入如1F001" clearable />
        </el-form-item>

        <el-form-item label="桌位" prop="seats">
          <el-select v-model="form.seats" placeholder="请选择..." clearable>
            <el-option
                v-for="location in locationOptions"
                :key="location.label"
                :label="location.label"
                :value="location.label"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="桌型" prop="tableType">
          <el-select v-model="form.tableType" placeholder="请选择..." clearable>
            <el-option
                v-for="type in tableTypeOptions"
                :key="type.id"
                :label="type.name"
                :value="type.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="使用状态" prop="usageStatus">
          <el-radio-group v-model="form.usageStatus">
            <el-radio :label="1">使用</el-radio>
            <el-radio :label="0">空闲</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="启用状态" prop="enabledStatus">
          <el-switch
              v-model="form.enabledStatus"
              active-text="启用"
              inactive-text="禁用"
              :active-value="1"
              :inactive-value="0"
          />
        </el-form-item>

        <!-- 二维码生成区域 -->
        <el-form-item label="二维码">
          <div class="qr-code-section">
            <el-button
                type="primary"
                :disabled="qrCodeGenerated"
                @click="generateQRCode"
            >
              生成台桌点餐二维码
            </el-button>
            <p class="qr-code-notice">
              二维码只可生成一次，终身与此桌台绑定，如需更换二维码请删除桌台从新添加
            </p>
            <div class="qr-code-image" v-if="qrCodeGenerated">
              <img :src="qrCodeImage" alt="桌台二维码" />
              <p class="qr-code-text">桌台点餐二维码</p>
            </div>
          </div>
        </el-form-item>

        <!-- 底部按钮 -->
        <el-form-item class="form-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";
import {ElMessage} from "element-plus";

export default {
  name: 'CreateTable',
  data() {
    return {
      form: {
        id: '',
        storeId: '',
        tableNumber: '',
        seats: '',
        tableType: '',
        usageStatus: 0, // 初始值为 0 (空闲)
        enabledStatus: false,
        qrCode: ''
      },
      rules: {
        id: [
          { required: true, message: '请输入编号', trigger: 'blur' }
        ],
        storeId: [
          { required: true, message: '请选择所属门店', trigger: 'change' }
        ],
        tableNumber: [
          { required: true, message: '请输入桌号', trigger: 'blur' },
          { pattern: /^[0-9A-Za-z]+$/, message: '桌号格式不正确', trigger: 'blur' }
        ],
        seats: [
          { required: true, message: '请选择桌位', trigger: 'change' }
        ],
        tableType: [
          { required: true, message: '请选择桌型', trigger: 'change' }
        ]
      },
      storeOptions: [],
      locationOptions: [
        { value: '1', label: '大厅' },
        { value: '2', label: '包间' },
      ],
      tableTypeOptions: [],
      qrCodeGenerated: false,
      qrCodeImage: ''
    }
  },
  created() {
    this.getAllStores();
    this.getAllTableTypes();
  },
  methods: {
    // 生成二维码
    generateQRCode() {
      this.$confirm('确定要生成二维码吗? 生成后将无法更改', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const qrCodeUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=https://example.com/table/' + Math.random().toString(36).substring(2, 10);
        this.qrCodeImage = qrCodeUrl;
        this.form.qrCode = qrCodeUrl; // 更新 form.qrCode
        this.qrCodeGenerated = true;
        this.$message.success('二维码生成成功');
      }).catch(() => {
        this.$message.info('已取消生成');
      });
    },

    // 获取所有门店
    getAllStores() {
      axios.get(`store/getStoreName`).then(res => {
        this.storeOptions = res.data;
      });
    },

    // 获取所有桌型
    getAllTableTypes() {
      axios.get(`table/tableType/1/1000`).then(res => {
        this.tableTypeOptions = res.data.obj.data;
      });
    },

    // 提交表单
    handleSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 检查是否生成了二维码
          if (!this.qrCodeGenerated) {
            this.$confirm('尚未生成二维码，确定要继续提交吗?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.submitForm();
            }).catch(() => {
              this.$message.info('已取消提交');
            });
          } else {
            this.submitForm();
          }
        } else {
          this.$message.error('请填写完整表单');
          return false;
        }
      });
    },

    // 实际提交表单
    submitForm() {
      //调用API提交表单
      axios.post("/table/addTable", this.form).then(res => {
        if (res.data) {
          ElMessage.success(res.data.msg)
        }
      }).catch(err => {
        ElMessage.error("创建失败")
      })
      // 清空表单
      this.form = {
        id: '',
        storeId: '',
        tableNumber: '',
        seats: '',
        tableType: '',
        usageStatus: 0, // 初始值为 0 (空闲)
        enabledStatus: false,
        qrCode: ''
      };
      this.$router.push('/Alterable'); // 提交成功后跳转到桌位管理页面
    },

    // 取消
    handleCancel() {
      this.$confirm('确定要取消创建吗? 所有未保存的内容将丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.push('/table-management'); // 假设取消后跳转到桌位管理页面
      }).catch(() => {
        this.$message.info('已取消');
      });
    }
  }
}
</script>

<style scoped>
.create-table-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.form-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.el-form-item {
  margin-bottom: 22px;
}

.qr-code-section {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.qr-code-notice {
  font-size: 12px;
  color: #999;
  margin: 5px 0;
}

.qr-code-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 10px;
}

.qr-code-image img {
  width: 150px;
  height: 150px;
  border: 1px solid #eee;
  padding: 5px;
}

.qr-code-text {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.form-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}

.el-button {
  margin-left: 10px;
}
</style>
